#include "CH58x_common.h"
#include "RX8025T.h"
#include "app_i2c.h"

uint8_t decToBcd(uint8_t val)
{
	return ((val / 10 * 16) + (val % 10));
}
uint8_t bcdToDec(uint8_t val)
{
	return ((val / 16 * 10) + (val % 16));
}

uint8_t RX8025_read(uint8_t reg)
{
	uint8_t bufffer;
	i2c_write_to( RX8025_ADDR, &reg, 1, true, true);

	i2c_read_from( RX8025_ADDR, &bufffer, 1, true, 1);

	return bufffer;
}

void RX8025_write(uint8_t reg, uint8_t data)
{

	static uint8_t dataSend[2];
	dataSend[0] = reg;
	dataSend[1] = data;
	i2c_write_to( RX8025_ADDR, dataSend, 2, true, true);
}

void RX8025SetDate(uint8_t year, uint8_t month, uint8_t day)
{
	RX8025_write( DAY_REG, decToBcd(day));
	RX8025_write( MONTH_REG, decToBcd(month));
	RX8025_write( YEAR_REG, decToBcd(year));
}

void RX8025GetTime(RX8025_TIME *time)
{
	time->hour = bcdToDec(RX8025_read( HOUR_REG));
	time->minutes = bcdToDec(RX8025_read( MINUTES_REG));
	time->seconds = bcdToDec(RX8025_read( SECONDS_REG));
	time->day = bcdToDec(RX8025_read( DAY_REG));
	time->month = bcdToDec(RX8025_read( MONTH_REG));
	time->year = bcdToDec(RX8025_read( YEAR_REG));
}

void RX8025SetTime(uint8_t hour, uint8_t minutes, uint8_t seconds)
{
	RX8025_write( HOUR_REG, decToBcd(hour));
	RX8025_write( MINUTES_REG, decToBcd(minutes));
	RX8025_write( SECONDS_REG, decToBcd(seconds));
}
void RX8025SetTimerPerMinute(void)
{
	RX8025_write( EXT_REG, 0x20);
	RX8025_write( FLG_REG, 0x00);
	RX8025_write( CT_REG, 0x60);
}

void RX8025Init(void)
{
	RX8025_read(0x00);
}

void RX8025ReadAll(uint8_t *temp)
{
	for (int i = 0; i < 7; i++)
			{
		temp[i] = bcdToDec(RX8025_read(i));
	}
}

